package com.example.cofeed.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ObjectUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.example.cofeed.R;
import com.example.cofeed.api.ApiService;
import com.example.cofeed.base.BaseActivity;
import com.example.cofeed.callback.DialogCallback;
import com.example.cofeed.callback.LzyResponse;
import com.example.cofeed.constant.IntentKeyConstant;
import com.example.cofeed.constant.SputilsConstant;
import com.example.cofeed.entity.MsgDetails;
import com.example.cofeed.even.HomeRefreshEven;
import com.iflytek.cloud.ErrorCode;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechSynthesizer;
import com.iflytek.cloud.SynthesizerListener;
import com.lzy.okgo.model.Response;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by mqwang on 2017/9/24.
 */

public class DetailsActivity extends BaseActivity {
    @BindView(R.id.play_tv)
    TextView playTv;
    @BindView(R.id.content_tv)
    TextView contentTv;
    @BindView(R.id.unfold_layout)
    RelativeLayout unfoldLayout;
    @BindView(R.id.other_tv)
    TextView otherTv;
    private boolean isShow;
    private String msgId;
    private MsgDetails msgDetails;

    private SpeechSynthesizer mTts;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_details;
    }

    @Override
    protected void init(Bundle savedInstanceState, View container) {
        msgId = getIntent().getStringExtra(IntentKeyConstant.MSG_ID);
        getData();

        int anInt = SPUtils.getInstance().getInt(SputilsConstant.CONTENT_FONT_SIZE, 1);
        contentTv.setMovementMethod(ScrollingMovementMethod.getInstance());
        switch (anInt){
            case 0:
                contentTv.setTextSize(SizeUtils.px2sp(this.getResources().getDimension(R.dimen.text_font_size1)));
                break;
            case 1:
                contentTv.setTextSize(SizeUtils.px2sp(this.getResources().getDimension(R.dimen.text_font_size2)));
                break;
            case 2:
                contentTv.setTextSize(SizeUtils.px2sp(this.getResources().getDimension(R.dimen.text_font_size3)));
                break;
            case 3:
                contentTv.setTextSize(SizeUtils.px2sp(this.getResources().getDimension(R.dimen.text_font_size4)));
                break;
            case 4:
                contentTv.setTextSize(SizeUtils.px2sp(this.getResources().getDimension(R.dimen.text_font_size5)));
                break;
        }

        // 初始化合成对象
        mTts = SpeechSynthesizer.createSynthesizer(this, mTtsInitListener);

    }

    /**
     * 初始化监听。
     */
    private InitListener mTtsInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
            Log.d(TAG, "InitListener init() code = " + code);
            if (code != ErrorCode.SUCCESS) {
                showToast("初始化失败,错误码："+code);
            } else {
                // 初始化成功，之后可以调用startSpeaking方法
                // 注：有的开发者在onCreate方法中创建完合成对象之后马上就调用startSpeaking进行合成，
                // 正确的做法是将onCreate中的startSpeaking调用移至这里
            }
        }
    };
    int playing = 0;

    /**
     * 合成回调监听。
     */
    private SynthesizerListener mTtsListener = new SynthesizerListener() {

        @Override
        public void onSpeakBegin() {
        }

        @Override
        public void onSpeakPaused() {
            playing = 0;

        }

        @Override
        public void onSpeakResumed() {
            playing = 1;

        }

        @Override
        public void onBufferProgress(int percent, int beginPos, int endPos,
                                     String info) {
            // 合成进度
//            mPercentForBuffering = percent;

        }

        @Override
        public void onSpeakProgress(int percent, int beginPos, int endPos) {
            // 播放进度
//            mPercentForPlaying = percent;

        }

        @Override
        public void onCompleted(SpeechError error) {
            if (error == null) {
//                showTip("播放完成");
                playing = 2;
                playTv.setText("播放完成");
            } else if (error != null) {
                showToast(error.getPlainDescription(true));
            }
        }

        @Override
        public void onEvent(int eventType, int arg1, int arg2, Bundle obj) {
            // 以下代码用于获取与云端的会话id，当业务出错时将会话id提供给技术支持人员，可用于查询会话日志，定位出错原因
            // 若使用本地能力，会话id为null
            //	if (SpeechEvent.EVENT_SESSION_ID == eventType) {
            //		String sid = obj.getString(SpeechEvent.KEY_EVENT_SESSION_ID);
            //		Log.d(TAG, "session id =" + sid);
            //	}
        }
    };


    private void getData() {
        ApiService.smsContent(this, msgId, new DialogCallback<LzyResponse<MsgDetails>>(this) {
            @Override
            public void onSuccess(Response<LzyResponse<MsgDetails>> response) {
                msgDetails = response.body().data;
                contentTv.setText(msgDetails.content);
                setMainTitle(msgDetails.tags);

                mTts.stopSpeaking();
                playing = 0;
                findViewById(R.id.play_layout).setVisibility(View.GONE);
            }
        });
    }

    void playVoice(String user_input){
        int code = mTts.startSpeaking(user_input, mTtsListener);
        if (code != ErrorCode.SUCCESS) {
            showToast("语音合成失败,错误码: " + code);
        }else{
            findViewById(R.id.play_layout).setVisibility(View.VISIBLE);
            playTv.setText("正在语音播放中，点击此处暂停播放");
            playing = 1;

        }
    }

    @OnClick({R.id.copy_tv, R.id.share_tv, R.id.voice_tv, R.id.error_correction_tv, R.id.collect_tv, R.id.delete_tv,
            R.id.previous_layout, R.id.other_layout, R.id.next_layout, R.id.play_tv, R.id.unfold_layout})
    public void onViewClicked(View view) {
        if (msgDetails == null) {
            return;
        }
        switch (view.getId()) {
            case R.id.copy_tv:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                // 将文本内容放到系统剪贴板里。
                cm.setText(contentTv.getText());
                showToast("复制成功");
                showUnfoldLy();
                break;
            case R.id.share_tv:
                showUnfoldLy();
                Intent shareIntent = new Intent(this, ShareActivity.class);
                startActivity(shareIntent);
                break;
            case R.id.voice_tv:
                showUnfoldLy();
                String user_input = contentTv.getText().toString();
                if (user_input.equals("")){
                    showToast("输入不能为空！");
                }else {
                    playVoice(user_input);
                }
                break;
            case R.id.error_correction_tv:
                Intent intent = new Intent(this, ErrorCorrectionActivity.class);
                intent.putExtra(IntentKeyConstant.MSG_ID, msgId);
                startActivity(intent);
                showUnfoldLy();
                break;
            case R.id.collect_tv:
                showUnfoldLy();
                if (msgDetails.favorites == 1){
                    showToast("已收藏");
                    return;
                }
                ApiService.favorite(msgId, new DialogCallback<LzyResponse<Object>>(this) {
                    @Override
                    public void onSuccess(Response<LzyResponse<Object>> response) {
                        msgDetails.favorites = 1;
                        showToast(response.body().msg);

                    }
                });
                break;
            case R.id.delete_tv:
                showUnfoldLy();
                new AlertDialog.Builder(this)
                        .setTitle("确认删除")
                        .setMessage("是否删除该条内容？\n删除后将无法找回！")
                        .setNegativeButton(R.string.cancel, null)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                showUnfoldLy();
                                ApiService.smsDelete(msgId, new DialogCallback<LzyResponse<Object>>(DetailsActivity.this) {
                                    @Override
                                    public void onSuccess(Response<LzyResponse<Object>> response) {
                                        EventBus.getDefault().post(new HomeRefreshEven());
                                        finish();

                                    }
                                });
                            }
                        }).show();
                break;
            case R.id.previous_layout:
                if (ObjectUtils.isEmpty(msgDetails.previousid) || msgDetails.previousid.equals("0")){
                    showToast("没有上一条信息");
                    return;
                }
                msgId = msgDetails.previousid;
                getData();
                break;
            case R.id.other_layout:
                showUnfoldLy();
                break;
            case R.id.next_layout:
                if (ObjectUtils.isEmpty(msgDetails.nextid) || msgDetails.nextid.equals("0")){
                    showToast("没有下一条信息");
                    return;
                }
                msgId = msgDetails.nextid;
                getData();
                break;
            case R.id.play_tv:
                switch (playing){
                    case 0:
                        playTv.setText("正在语音播放中，点击此处暂停播放");
                        mTts.resumeSpeaking();
                        playing = 1;
                        break;
                    case 1:
                        playTv.setText("语音暂停中，点击此处继续播放");
                        mTts.pauseSpeaking();
                        playing = 0;
                        break;
                    case 2:
                        playVoice(contentTv.getText().toString());
                        break;
                }
                break;
            case R.id.unfold_layout:
                showUnfoldLy();
                break;
        }
    }

    void showUnfoldLy(){
        if (isShow){
            isShow = false;
            unfoldLayout.setVisibility(View.GONE);
            otherTv.setCompoundDrawablesWithIntrinsicBounds(null, this.getResources().getDrawable(R.mipmap.xiangqing_zhankai), null, null);
        }else {
            isShow = true;
            unfoldLayout.setVisibility(View.VISIBLE);
            otherTv.setCompoundDrawablesWithIntrinsicBounds(null, this.getResources().getDrawable(R.mipmap.xiangqing_zhankai_down), null, null);
        }
    }

    @Override
    protected void onDestroy() {
//        audioTrack.release();
        super.onDestroy();
        if( null != mTts ){
            mTts.stopSpeaking();
            // 退出时释放连接
            mTts.destroy();
        }

    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

}
